// Copyright (c) 2011 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "net/http/server/comet/proxy_detect.h"

#include <glog/logging.h>

#include <map>
#include <string>

#include "base/init.h"
#include "net/http/server/comet/proxy_detect_manager.h"
#include "net/http/server/comet/request_helper.h"
#include "net/http/server/comet/session.h"

namespace sg {
namespace net {
namespace http {
namespace server {
namespace comet {

ProxyDetect::ProxyDetect(es::Request *request)
    : request_(request),
      timer_(2, std::bind(&ProxyDetect::PhaseTwoCallback, this)), type_(),
      padding_() {
  RequestHelper request_helper(request_);
  request_->GetQueryParam("TYPE", &type_);
  padding_ = type_ == "html" ? RequestHelper::SCRIPT : RequestHelper::NONE;
  CHECK(request_helper.StartChunk(padding_));
  CHECK(request_helper.SendChunk("11111", padding_));
  if (padding_ == RequestHelper::SCRIPT) {
    CHECK(request_helper.SendChunk(kIePadding, RequestHelper::NONE));
  }
}

void ProxyDetect::PhaseTwoCallback(void *proxy_detect) {
  ProxyDetect *pd = static_cast<ProxyDetect *>(proxy_detect);
  RequestHelper request_helper(pd->request_);
  CHECK(request_helper.SendChunk("2", pd->padding_));
  pd->Stop();
}

void ProxyDetect::ConnectionCloseCallback(void *proxy_detect) {
  ProxyDetect *pd = static_cast<ProxyDetect *>(proxy_detect);
  pd->request_ = NULL;
  pd->Stop();
}

void ProxyDetect::Stop() {
  timer_.Stop();
  if (request_ != NULL) {
    RequestHelper request_helper(request_);
    CHECK(request_helper.EndChunk(padding_));
  }
  // TODO(ahochhaus):
  // ProxyDetectManager::Remove(ProxyDetectManager::ProxyDetectRefCntPtr(this));
}

}  // namespace comet
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg
